$(document).ready(function () {
  initMap();
  drawTrendChart();
  analysisChart();
  getYsyToken();
  queryDeviceCount();
  queryAlarmList();
  queryDeviceData();
});
// 初始化地图
var map;
var mouseTool = null; //地图组件实例
var infoWindow = null;
initMap = () => {
  $('#tipinput').val('');

  map = new AMap.Map('map', {
    center: [101.497147, 36.643514],
    zoom: 9.5,
    mapStyle: 'amap://styles/grey',
  });

  //实时路况图层
  var satellite = new AMap.TileLayer.Satellite();

  satellite.setMap(map);

  var isVisible = false;
  satellite.hide();
  function toggle() {
    if (isVisible) {
      satellite.hide();
      isVisible = false;
    } else {
      satellite.show();
      isVisible = true;
    }
  }

  document.getElementById('map-btn').addEventListener('click', toggle);

  AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
    var poiPicker = new PoiPicker({
      input: 'tipinput',
      city: '西宁市', //城市
    });

    //初始化poiPicker
    poiPickerReady(poiPicker);
  });
  function poiPickerReady(poiPicker) {
    window.poiPicker = poiPicker;

    var marker = new AMap.Marker();

    infoWindow = new AMap.InfoWindow({
      anchor: 'middle-right',
    });

    //选取了某个POI
    poiPicker.on('poiPicked', function (poiResult) {
      var source = poiResult.source,
        poi = poiResult.item,
        info = {
          source: source,
          id: poi.id,
          name: poi.name,
          location: poi.location.toString(),
          address: poi.address,
        };

      marker.setMap(map);
      infoWindow.setMap(map);

      marker.setPosition(poi.location);
      infoWindow.setPosition(poi.location);

      const lData = {
        名称: info.name,
        地址: info.address,
        坐标: info.location,
      };
      infoWindow.setContent(
        '位置信息: <pre>' + JSON.stringify(lData, null, 2) + '</pre>'
      );
      infoWindow.open(map, marker.getPosition());

      map.setCenter(marker.getPosition());
    });
  }

  /*单击地图事件*/
  map.on('click', function (e) {
    infoWindow.close();
  });

  ajax('../static/json/湟中区.json', function (err, geoJSON) {
    if (!err) {
      var geojson = new AMap.GeoJSON({
        geoJSON: geoJSON,
        // 还可以自定义getMarker和getPolyline
        getPolygon: function (geojson, lnglats) {
          // 计算面积
          var area = AMap.GeometryUtil.ringArea(lnglats[0]);

          return new AMap.Polygon({
            path: lnglats,
            fillOpacity: 0.1, // 面积越大透明度越高
            strokeColor: '#65D0E0',
            fillColor: '#2FC7FF',
          });
        },
      });
      map.add(geojson);
      // map.setFitView();
      log.success('GeoJSON 数据加载完成');
    } else {
      log.error('GeoJSON 服务请求失败');
    }
  });

  addMarker2Map('');
};

// 将设备图标定位至地图
var overlayGroups;
addMarker2Map = (type) => {
  if (overlayGroups) {
    map.remove(overlayGroups);
  }

  AjaxRequest('/data/device/map/status?type=' + type, callBack);

  function callBack(result) {
    if (result.status == 200) {
      var markers = [];
      var data = result.result;
      var icon = '';
      var s = '';

      data.forEach((e) => {
        s = '';
        if (e.eventType == null) {
          e.eventType = 0;
        }

        if (!e.eventType == 0) {
          s = '_alarm';
        }

        if (e.longitude) {
          icon = '../static/img/map' + e.type + s + '.png';
          // 创建点实例
          var marker = new AMap.Marker({
            position: new AMap.LngLat(e.longitude, e.latitude),
            icon: icon,
          });

          marker.deviceId = e.deviceId;
          marker.Dtype = e.type;
          marker.code = e.code;
          marker.name = e.name;

          markers.push(marker);

          // infoWindow.setContent('位置信息: <pre>' + JSON.stringify(lData, null, 2) + '</pre>');

          marker.on('click', function (e) {
            if (e.target.Dtype == 1) {
              AjaxRequest(
                '/data/device/water/status/info?deviceId=' + e.target.deviceId,
                callBack
              );

              function callBack(result) {
                if (result.status == 200) {
                  var data = result.result;

                  layer.open({
                    type: 1,
                    title: false, //不显示标题栏
                    closeBtn: 1,
                    shadeClose: true,
                    // , area: '300px;'
                    shade: 0.7,
                    id: 'LAY_layuipro', //设定一个id，防止重复弹出
                    btnAlign: 'c',
                    moveType: 1, //拖拽模式，0或者1
                    content: `<div class="map-infoWindow">
                                        <div class="map-tab">
                                            <div class="active" data-type="1">设备概况</div>
                                            <div data-type="2">告警记录</div>
                                        </div>
                                        <div class="infoWindow-msg">
                                            <ul>
                                                <li>安装地址：${
                                                  data.name || ''
                                                }</li>
                                                <li>设备编号：${
                                                  data.code || ''
                                                }</li>
                                                <li>设备状态：${
                                                  data.eventTypeDesc || ''
                                                }</li>
                                                <li>监测浊度：${
                                                  data.ntu || ''
                                                }</li>
                                                <li>监测温度：${
                                                  data.temperature || ''
                                                }</li>
                                                <li>上报时间：${
                                                  data.dataTime || ''
                                                }</li>
                                                <li>信号强度：${
                                                  data.signal || ''
                                                }</li>
                                            </ul>
                                            <div id="map-chart"></div>
                                        </div>
                                        <div class="infoWindow-alarm"></div>
                                    </div>`,
                  });

                  mapDeviceChart(e.target.deviceId);

                  $('.map-tab>div').click(function (ev) {
                    $(ev.currentTarget)
                      .addClass('active')
                      .siblings()
                      .removeClass('active');
                    var type = $(ev.currentTarget).data().type;
                    switch (type) {
                      case 1:
                        $('.infoWindow-alarm').hide();
                        $('.infoWindow-msg').show();

                        break;
                      case 2:
                        $('.infoWindow-alarm').attr('style', 'display:flex;');
                        $('.infoWindow-msg').hide();

                        AjaxRequest(
                          '/alarm/list?pageNum=1&pageSize=4&name=&code=' +
                            e.target.code +
                            '&type=&beginDate=&endDate=&dealStatus=1',
                          alarmCallBack
                        );

                        function alarmCallBack(result) {
                          if (result.status == 200) {
                            var data = result.result.data;
                            if (data.length == 0) {
                              $('.infoWindow-alarm')
                                .empty()
                                .append('<img src="../static/img/nodata.png">');
                            } else {
                              $('.infoWindow-alarm')
                                .empty()
                                .append(
                                  data.reduce((x, y) => {
                                    return (
                                      x +
                                      `<div class="infoWindow-list-item">
                                                                                <div onclick="showPhotoWindow('${y.alarmTime}','${y.alarmImage}')">
                                                                                    <img src="/images/${y.alarmImage}" title="放大">
                                                                                </div>
                                                                                <div>告警设备：${y.deviceName}</div>
                                                                                <div>告警描述：${y.alarmDesc}</div>
                                                                                <div>告警时间：${y.alarmTime}</div>
                                                                            </div>`
                                    );
                                  }, ``)
                                );
                            }
                          }
                        }
                        break;

                      default:
                        break;
                    }
                  });
                }
              }
            } else {
              AjaxRequest(
                '/data/device/ys/live/address/get',
                callBack,
                {
                  code: e.target.code,
                  protocol: 1,
                  quality: 2,
                },
                'post'
              );

              function callBack(result) {
                if (result.status == 200) {
                  layer.open({
                    type: 1,
                    title: false, //不显示标题栏
                    closeBtn: 1,
                    shadeClose: true,
                    // , area: '300px;'
                    shade: 0.7,
                    id: 'LAY_layuipro', //设定一个id，防止重复弹出
                    btnAlign: 'c',
                    moveType: 1, //拖拽模式，0或者1
                    content: `
                                        <div class="map-infoWindow">
                                            <div class="map-tab">
                                                <div class="active" data-type="1">设备概况</div>
                                                <div data-type="2">告警记录</div>
                                            </div>
                                            <div class="infoWindow-msg">
                                                <div id="map-video"></div>
                                                <div  id="map-videoname">${e.target.name}</div>
                                            </div>
                                            <div class="infoWindow-alarm"></div>
                                        </div>`,
                  });

                  setTimeout(() => {
                    new EZUIKit.EZUIKitPlayer({
                      id: 'map-video', // 视频容器ID
                      accessToken: accessToken,
                      url: result.result,
                      template: 'simple',
                    });
                  }, 300);

                  $('.map-tab>div').click(function (ev) {
                    $(ev.currentTarget)
                      .addClass('active')
                      .siblings()
                      .removeClass('active');
                    var type = $(ev.currentTarget).data().type;
                    switch (type) {
                      case 1:
                        $('.infoWindow-alarm').hide();
                        $('.infoWindow-msg').show();

                        break;
                      case 2:
                        $('.infoWindow-alarm').attr('style', 'display:flex;');
                        $('.infoWindow-msg').hide();

                        AjaxRequest(
                          '/alarm/list?pageNum=1&pageSize=4&name=&code=' +
                            e.target.code +
                            '&type=&beginDate=&endDate=&dealStatus=1',
                          alarmCallBack
                        );

                        function alarmCallBack(result) {
                          if (result.status == 200) {
                            var data = result.result.data;
                            if (data.length == 0) {
                              $('.infoWindow-alarm')
                                .empty()
                                .append('<img src="../static/img/nodata.png">');
                            } else {
                              $('.infoWindow-alarm')
                                .empty()
                                .append(
                                  data.reduce((x, y) => {
                                    return (
                                      x +
                                      `<div class="infoWindow-list-item">
                                                                                <div onclick="showPhotoWindow('${y.alarmTime}','${y.alarmImage}')">
                                                                                    <img src="/images/${y.alarmImage}" title="放大">
                                                                                </div>
                                                                                <div>告警设备：${y.deviceName}</div>
                                                                                <div>告警描述：${y.alarmDesc}</div>
                                                                                <div>告警时间：${y.alarmTime}</div>
                                                                            </div>`
                                    );
                                  }, ``)
                                );
                            }
                          }
                        }
                        break;

                      default:
                        break;
                    }
                  });
                } else {
                  layer.msg('设备不在线');
                }
              }
            }
          });
        }
      });
      overlayGroups = new AMap.OverlayGroup(markers);
      map.add(overlayGroups);
    }
  }
};
// 获取萤石云token
var accessToken;
function getYsyToken() {
  AjaxRequest('/data/device/ys/token/get', callBack, {}, 'post');
  function callBack(result) {
    if (result.status == 200) {
      accessToken = result.result;
    }
  }
}

$('.map-overview-item').click(function (e) {
  var type = $(e.currentTarget).data().type;

  $(e.currentTarget).addClass('active').siblings().removeClass('active');

  addMarker2Map(type);
});

// 地图定点展开趋势
mapDeviceChart = (deviceId) => {
  AjaxRequest(
    '/data/device/water/trend/list?deviceId=' +
      deviceId +
      '&beginDate=' +
      getBeforeDate(-7) +
      '&endDate=' +
      getBeforeDate(0),
    callBack
  );

  function callBack(result) {
    if (result.status == 200) {
      var ntu = [],
        xdate = [];
      result.result.forEach((e) => {
        ntu.push(e.ntu);
        xdate.push(e.dataTime.substring(5));
      });

      var option = {
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          left: '5%',
          right: '5%',
          top: '15%',
          bottom: '5%',
          containLabel: true,
        },
        //	    toolbox: {
        //	        feature: {
        //	            saveAsImage: {}
        //	        }
        //	    },
        xAxis: {
          type: 'category',
          boundaryGap: true, //坐标轴两边留白
          data: xdate,
          axisLabel: {
            //坐标轴刻度标签的相关设置。
            //	margin:15,
            textStyle: {
              color: '#eeeeee',
              fontStyle: 'normal',
              fontFamily: '微软雅黑',
              fontSize: 12,
            },
            formatter: function (params) {
              var newParamsName = '';
              var paramsNameNumber = params.length;
              var provideNumber = 6; //一行显示几个字
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
              if (paramsNameNumber > provideNumber) {
                for (var p = 0; p < rowNumber; p++) {
                  var tempStr = '';
                  var start = p * provideNumber;
                  var end = start + provideNumber;
                  if (p == rowNumber - 1) {
                    tempStr = params.substring(start, paramsNameNumber);
                  } else {
                    tempStr = params.substring(start, end) + '\n';
                  }
                  newParamsName += tempStr;
                }
              } else {
                newParamsName = params;
              }
              return newParamsName;
            },
            //rotate:50,
          },
          axisTick: {
            //坐标轴刻度相关设置。
            show: false,
          },
          axisLine: {
            //坐标轴轴线相关设置
            lineStyle: {
              color: '#427680',
              width: 2,
            },
          },
          splitLine: {
            //坐标轴在 grid 区域中的分隔线。
            show: false,
            lineStyle: {
              color: '#E5E9ED',
              // 	opacity:0.1
            },
          },
        },
        yAxis: [
          {
            type: 'value',
            // min: 0,
            // max: 400,
            // splitNumber: 5,
            axisLabel: {
              textStyle: {
                color: '#5787C0',
                fontStyle: 'normal',
                fontFamily: '微软雅黑',
                fontSize: 12,
              },
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#427680',
                width: 2,
              },
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'solid',
                color: 'rgba(56, 117, 174, 0.5)',
                // 	opacity:0.1
              },
            },
          },
        ],
        series: [
          {
            name: '浊度',
            type: 'line',
            smooth: true,
            symbol: 'none',
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    offset: 1,
                    color: '#FFCFAD',
                  },
                  {
                    offset: 0,
                    color: '#FF8818',
                  },
                ]),
                shadowColor: '#FFA85B',
                shadowBlur: 20,
                borderColor: '#FFA85B',
                borderWidth: 2,
                lineStyle: {
                  color: '#FFA85B',
                  width: 2,
                },
              },
            },
            data: ntu,
          },
        ],
      };

      var chart = echarts.init(document.getElementById('map-chart'));
      chart.setOption(option);
    }
  }
};

// 获取各种设备数量
queryDeviceCount = () => {
  AjaxRequest('/data/device/type/count', callBack);

  function callBack(result) {
    if (result.status == 200) {
      var total = 0;
      result.result.forEach((e) => {
        $('#item-count-' + e.type).html(e.total);
        total = total + e.total;
      });
      $('#item-count-0').html(total);
    }
  }
};

// 设备实时监测轮播
queryDeviceData = () => {
  AjaxRequest(
    '/data/device/water/status/list?pageNum=1&pageSize=50&name=&code=&eventType=',
    callBack
  );

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result.data;

      var l = 0;
      var length = data.length - 1;
      $('.realtime-item')
        .eq(0)
        .find('.realtime-data')
        .html(data[l].name || '-');
      $('.realtime-item')
        .eq(1)
        .find('.realtime-data')
        .html(data[l].code || '-');
      $('.realtime-item')
        .eq(2)
        .find('.realtime-data')
        .html(data[l].eventTypeDesc || '-');
      $('.realtime-item')
        .eq(3)
        .find('.realtime-data')
        .html(data[l].ntu || '-');
      $('.realtime-item')
        .eq(4)
        .find('.realtime-data')
        .html(data[l].temperature || '-');
      $('.realtime-item')
        .eq(5)
        .find('.realtime-data')
        .html(data[l].dataTime || '-');
      $('.realtime-item')
        .eq(6)
        .find('.realtime-data')
        .html(data[l].signal || '-');

      setInterval(() => {
        if (l < length) {
          l++;
        } else {
          l = 0;
        }

        $('.realtime-list').removeClass('animate__animated animate__flipInX');
        var timer = setTimeout(() => {
          $('.realtime-list').addClass('animate__animated animate__flipInX');
          $('.realtime-item')
            .eq(0)
            .find('.realtime-data')
            .html(data[l].name || '-');
          $('.realtime-item')
            .eq(1)
            .find('.realtime-data')
            .html(data[l].code || '-');
          $('.realtime-item')
            .eq(2)
            .find('.realtime-data')
            .html(data[l].eventTypeDesc || '-');
          $('.realtime-item')
            .eq(3)
            .find('.realtime-data')
            .html(data[l].ntu || '-');
          $('.realtime-item')
            .eq(4)
            .find('.realtime-data')
            .html(data[l].temperature || '-');
          $('.realtime-item')
            .eq(5)
            .find('.realtime-data')
            .html(data[l].dataTime || '-');
          $('.realtime-item')
            .eq(6)
            .find('.realtime-data')
            .html(data[l].signal || '-');
        }, 500);
      }, 10000);
    }
  }
};

// 告警列表

queryAlarmList = () => {
  AjaxRequest(
    '/alarm/list?pageNum=1&pageSize=6&name=&code=&type=&beginDate=&endDate=&dealStatus=1',
    callBack
  );

  function callBack(result) {
    if (result.status == 200) {
      var list = result.result.data;

      if (list.length == 0) {
        $('.alarm-list')
          .empty()
          .append(
            '<div style="width: 100%;height: 2.5rem;display: flex;align-items: center;justify-content: center;"><img src="../static/img/nodata.png"></div>'
          );
      } else {
        $('.alarm-list')
          .empty()
          .append(
            list.reduce((x, y) => {
              return (
                x +
                `<div class="alarm-list-item">
                                <div>${y.deviceName}</div>
                                <div>${y.eventTypeDesc}</div>
                                <div>${y.alarmTime}</div>
                            </div>`
              );
            }, ` <div class="alarm-list-item"><div>告警设备</div><div>告警描述</div><div>告警时间</div></div>`)
          );
      }
    }
  }
};

$('.data-more').click(function () {
  window.open('../html/realtimedata.html');
});

$('.alarm-more').click(function () {
  window.open('../html/alarmmanagement.html');
});

// 近三十天告警趋势
drawTrendChart = () => {
  AjaxRequest(
    '/data/alarm/type/trend/count?type=1&begin=' +
      getBeforeDate(-30) +
      '&end=' +
      getBeforeDate(0),
    callBack
  );

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result;
      var xData = [],
        totalArr = [],
        ntuArr = [],
        areaArr = [];
      data.forEach((e) => {
        xData.push(e.days);
        totalArr.push(e.total);
        ntuArr.push(e.ntu);
        areaArr.push(e.area);
      });

      var option = {
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          // 设置图例不默认选中
          selected: {
            告警总数: false,
            浊度告警: true,
            悬浮物告警: true,
          },
          top: '10',
          right: '5%',
          icon: 'rect',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            align: 'center',
            color: '#ddd',
            fontSize: 12,
          },
        },

        grid: {
          left: '8%',
          top: 50,
          bottom: 30,
          right: '5%',
          containLabel: false,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xData,
          axisLine: { show: false },
          axisLabel: { color: '#99A4B7' },
          axisTick: { show: false },
          splitLine: {
            show: false,
          },
        },
        yAxis: {
          name: '次',
          type: 'value',
          axisLine: { show: false },
          axisLabel: { color: '#99A4B7' },
          axisTick: { show: false },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: 'rgba(255,255,255,0.1)',
              dashOffset: 1,
            },
          },
        },
        series: [
          {
            name: '告警总数',
            type: 'line',
            data: totalArr,
            symbol: 'none',
            markPoint: {
              symbolSize: '29',
              symbol:
                'image://',
              label: {
                show: false,
              },
              data: [
                {
                  type: 'max',
                  name: '最大值',
                },
              ],
            },
            itemStyle: {
              normal: {
                borderWidth: 3,
                //4个参数用于配置渐变色的起止位置, 这4个参数依次对应右/下/左/上四个方位
                color: '#ff4545',
              },
            },
            areaStyle: {
              normal: {
                origin: 'start',
                color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                  {
                    offset: 0,
                    color: 'rgba(10, 71, 118, 0)',
                  },
                  {
                    offset: 1,
                    color: 'rgba(10, 71, 118, 0.71)',
                  },
                ]),
              },
            },
          },
          {
            name: '浊度告警',
            type: 'line',
            data: ntuArr,
            symbol: 'none',
            markPoint: {
              symbolSize: '15',
              symbol:
                'image://',
              label: {
                show: false,
              },
              data: [
                {
                  type: 'max',
                  name: '最大值',
                },
              ],
            },
            itemStyle: {
              normal: {
                borderWidth: 1,
                //4个参数用于配置渐变色的起止位置, 这4个参数依次对应右/下/左/上四个方位
                color: '#eeb033',
              },
            },
          },
          {
            name: '悬浮物告警',
            type: 'line',
            data: areaArr,
            symbol: 'none',
            markPoint: {
              symbolSize: '15',
              symbol:
                'image://',
              label: {
                show: false,
              },
              data: [
                {
                  type: 'max',
                  name: '最大值',
                },
              ],
            },
            itemStyle: {
              normal: {
                borderWidth: 1,
                //4个参数用于配置渐变色的起止位置, 这4个参数依次对应右/下/左/上四个方位
                color: '#3F91D8',
              },
            },
          },
        ],
      };

      var chart = echarts.init(document.getElementById('trend-chart'));
      chart.setOption(option);
    }
  }
};

// 告警占比

ratioChart = (res) => {
  var data = [
    {
      type: '浊度',
      loss: res.ntu || 0,
    },
    {
      type: '悬浮物',
      loss: res.area || 0,
    },
  ];
  const series = [];
  const centerY = 50; // 原点y轴的单位距离
  const centerYOffset = 5; // 原点偏移
  const centerX = 30; // 原点x轴的单位距离

  let chartList = [];

  $.each(data, function (key, item) {
    chartList.push({ name: item.type, value: item.loss });
  });
  var sumValue = 0;
  chartList.map((item) => {
    sumValue += item.value;
  });

  var colorList = ['#1DD4FF', '#EEB033'];
  chartList.forEach((item, index) => {
    const radius = 60;
    const borderWidth = 10;
    const titleSize = 14;
    const valueSize = 14;
    const ratio = 0;
    const detail = 0;
    if (sumValue != 0) {
      ratio = (item.value / sumValue) * 360;
      detail = (item.value / res.total).toFixed(2) * 100;
    }
    // const ratio = (item.value / sumValue) * 360;
    const center = [
      centerX * (index * 1.5) + centerX + '%',
      centerY * Math.floor(index / 2) + centerY - centerYOffset + '%',
    ];
    console.log(radius);
    series.push(
      {
        // 内圆背景
        type: 'pie',
        radius: radius + '%',
        center,
        z: 1,
        itemStyle: {
          color: '#0B1F28',
        },
        label: {
          show: false,
        },
        tooltip: {
          show: false,
        },
        data: [100],
      },
      {
        //  内圆边框
        type: 'pie',
        radius: [radius + '%', radius + 2 + '%'],
        center,
        // clockWise: false,
        z: 2,
        itemStyle: {
          color: '#192E38',
        },
        label: {
          show: false,
        },
        data: [100],
      },
      {
        // 进度
        type: 'gauge',
        radius: radius - 25 + '%',
        startAngle: 90,
        endAngle: ~ratio + 91,
        center,
        z: 3,
        axisLine: {
          lineStyle: {
            width: borderWidth,
            color: [
              [
                1,
                new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: colorList[index] },
                  { offset: 1, color: colorList[index] },
                ]),
              ],
            ],
          },
        },
        pointer: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
        detail: {
          valueAnimation: true,
          formatter: () => `${detail}%`,
          offsetCenter: [0, 0],
          fontSize: valueSize,
          fontWeight: 'bolder',
          color: colorList[index],
        },
        title: {
          offsetCenter: [0, '250%'],
          fontSize: titleSize,
          color: '#ddd',
        },
        data: [item],
      },
      {
        // 内圆刻度
        type: 'gauge',
        startAngle: 90,
        endAngle: -270,
        radius: radius + '%',
        splitNumber: 20,
        z: 4,
        center,
        axisLine: {
          show: false,
        },
        pointer: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          distance: -3,
          length: 13,
          lineStyle: {
            color: '#192E38',
            width: 8,
          },
        },
        axisLabel: {
          show: false,
        },
      },
      {
        // 外圆
        type: 'pie',
        z: 2,
        radius: [radius - 25 + '%', radius - 35 + '%'],
        center,
        // clockWise: false,
        itemStyle: {
          color: '#284551',
        },
        label: {
          show: false,
        },
        data: [100],
      }
    );
  });

  option = {
    animation: true,
    series: series,
  };

  var chart = echarts.init(document.getElementById('ratio-chart'));
  chart.setOption(option);
};

// 今年告警次数分析
analysisChart = () => {
  AjaxRequest(
    '/data/alarm/type/count?type=3&begin=' + new Date().getFullYear() + '&end=',
    callBack
  );

  function callBack(result) {
    if (result.status == 200) {
      var data = result.result;

      ratioChart(data);

      let bjlxChartData = {
        areaName: ['告警总次数', '悬浮物告警次数', '浊度告警次数'],
        eventCount: [data.total, data.area, data.ntu],
      };
      let max = Math.max(...bjlxChartData.eventCount);
      var maxArr = [];
      for (var i = 0; i < bjlxChartData.eventCount.length; i++) {
        maxArr.push(max);
      }
      var option = {
        grid: {
          left: '5%',
          top: 30,
          right: '0',
          bottom: '0%',
          containLabel: true,
        },
        xAxis: [
          {
            show: false,
          },
        ],
        yAxis: [
          {
            axisTick: 'none',
            axisLine: 'none',
            inverse: true,
            offset: '0',
            axisLabel: {
              inside: true,
              textStyle: {
                color: '#01C1E9',
                fontSize: 12,
                verticalAlign: 'bottom',
                align: 'left',
                padding: [0, 0, 20, 0],
              },
              formatter: function (value) {
                return value;
              },
            },
            data: bjlxChartData.areaName,
          },
          {
            axisTick: 'none',
            axisLine: 'none',
            inverse: true,
            axisLabel: {
              textStyle: {
                color: '#01C1E9',
                fontSize: 12,
                verticalAlign: 'bottom',
                align: 'right',
                padding: [0, 0, 10, 0],
              },
              formatter: function (value, index) {
                return value + '次';
              },
            },
            data: bjlxChartData.eventCount,
          },
          {
            axisLine: {
              lineStyle: {
                color: 'rgba(0,0,0,0)',
              },
            },
            data: [],
          },
        ],
        series: [
          {
            name: '条',
            type: 'bar',
            stack: '圆',
            yAxisIndex: 0,
            // data: data,
            data: bjlxChartData.eventCount,
            barWidth: 3,
            itemStyle: {
              normal: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 1,
                  y2: 0,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#26D0F200', // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: '#26D0F2ff', // 100% 处的颜色
                    },
                  ],
                },
              },
            },
            z: 2,
          },
          {
            name: 'XXX',
            type: 'pictorialBar',
            symbol:
              'image://',
            symbolSize: [20, 20],
            symbolPosition: 'end',
            symbolOffset: [20, 0],
            z: 12,
            itemStyle: {
              normal: {
                color: '#fff',
              },
            },
            data: bjlxChartData.eventCount,
          },
          {
            name: '背景',
            type: 'bar',
            barWidth: 3,
            z: 1,
            barGap: '-100%',
            data: maxArr,
            itemStyle: {
              normal: {
                color: '#222935',
              },
            },
          },
        ],
      };
      var chart = echarts.init(document.getElementById('analysis-chart'));
      chart.setOption(option);
    }
  }
};

//地图工具
$('.tool-box-item').click(function (e) {
  $(e.currentTarget).addClass('active').siblings().removeClass('active');
  let type = $('.tool-box-item.active')[0].dataset.type;

  if (mouseTool != null) {
    mouseTool.close();
  }

  switch (type) {
    case 'reset':
      map.setZoomAndCenter(9.5, [101.497147, 36.643514]);
      break;
    case 'enlarge':
      map.zoomIn();
      // mapZoomIn();
      break;
    case 'narrow':
      map.zoomOut();
      // mapZoomOut();
      break;
    case 'position':
      drawMarker();
      break;
    case 'distance':
      layer.msg('双击地图完成绘制', {
        time: 1500,
      });
      drawPolyline();
      break;
    case 'screenshot':
      screenshot();
      break;
    case 'area':
      layer.msg('双击地图完成绘制', {
        time: 1500,
      });
      drawPolygon();
      break;
    case 'clear':
      clearMap();
      break;
    default:
      break;
  }
});

// 屏幕截图
function screenshot() {
  setTimeout(() => {
    layer.msg('正在抓取屏幕信息，请稍后...');
  }, 300);

  html2canvas(document.querySelector('body')).then((canvas) => {
    var link = document.createElement('a');
    var imgData = canvas.toDataURL();
    var blob = dataURLtoBlob(imgData);
    var objurl = URL.createObjectURL(blob);
    link.download = '湟中区饮水净化' + new Date().getTime() + '.png';
    link.href = objurl;
    link.click();

    function dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime,
      });
    }
  });
}

// 地图放大
function mapZoomIn() {
  mouseTool = new AMap.MouseTool(map);
  mouseTool.rectZoomIn();
}

// 地图缩小
function mapZoomOut() {
  mouseTool = new AMap.MouseTool(map);
  mouseTool.rectZoomOut();
}

// 地图定点
function drawMarker() {
  mouseTool = new AMap.MouseTool(map);
  mouseTool.marker();

  mouseTool.on('draw', function (event) {
    layer.alert(
      '您选中的坐标为：' +
        event.obj.getPosition().lng +
        ',' +
        event.obj.getPosition().lat
    );
  });
}

// 地图画线测距
function drawPolyline() {
  mouseTool = new AMap.MouseTool(map);
  mouseTool.rule();
}

// 地图画多边形测面积
function drawPolygon() {
  mouseTool = new AMap.MouseTool(map);
  mouseTool.measureArea();
}

// 清除地图上所有覆盖物
function clearMap() {
  map.clearMap();
}
